package com.itheima.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class SercurityUserService implements UserDetailsService {

    //将map模拟为一个数据库
    private Map map = new HashMap<>();

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public void init(){
        User user1 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword(passwordEncoder.encode("1234"));
        map.put(user1.getUsername(),user1);

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword(passwordEncoder.encode("1234"));
        map.put(user2.getUsername(),user2);

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //初始化数据库
        init();

        //模拟通过用户名去数据库查询用户
        User user = (User) map.get(username);

        //赋予权限
        List<GrantedAuthority> list = new ArrayList<>();

        if (user.getUsername().equals("zhangsan")){
            list.add(new SimpleGrantedAuthority("add"));
            list.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        /**
         *
         * 设置授权,其设置的命名规则：
         *      如果是设置角色：全部是大写字母，前缀使用ROLE_,ROLE_ADMIN,ROLE_MANAGER
         *      如果是设置权限：字母小写   add、update、delete
         *
         */
        //list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        //list.add(new SimpleGrantedAuthority("add"));


        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode1 = passwordEncoder.encode("1234");
        String encode2 = passwordEncoder.encode("1234");

        System.out.println(encode1);
        System.out.println(encode2);

        boolean flag1 = passwordEncoder.matches("1234", encode1);
        boolean flag2 = passwordEncoder.matches("1234", encode2);

        System.out.println(flag1);
        System.out.println(flag2);

    }
}
